//index.js
//获取应用实例
const userService = require('../../services/userService');
var app = getApp()
Page({
  data: {
    red_list: {},
    datalist: [],
    page: 1,
    totalPage: 0,
    error:false,
    errorMsg: ''
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../kefu/kefu'
    })
  },

  bindScanCode: function() {
    app.bindScanCode();
  },

  onPullDownRefresh: function(){
    var that = this;
    if((this.data.page + 1)>this.data.totalPage) {
      this.setData({
        error:true,
        errorMsg: '没有更多数据'
      });
      setTimeout(function(){
        that.setData({
          error:false
        });
      },2000);
      wx.stopPullDownRefresh();
      return;
    }
    this.setData({
      page: this.data.page + 1
    })
    this._getRedList(this.data.page);
  },

  _getRedList: function(page){
    var that = this;
    var user = wx.getStorageSync('user');
    if(user) {
      wx.showLoading({
        title: '加载数据...'
      });
      userService.userRed(user.openid,page).then((data) => {
          var data = data.data;
          var red_list = data.red_list;
          var totalPage = Math.ceil(red_list.total/red_list.per_page);
          that.data.datalist = that.data.datalist.concat(red_list.data);
          red_list.data = that.data.datalist; 
          that.setData({
            red_list: red_list,
            totalPage: totalPage
          });
           wx.hideLoading();
        }, (error) => {
        });
      }
  },
  onLoad: function () {
    this._getRedList(1);
    var that = this;
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      //更新数据
      that.setData({
        userInfo:userInfo
      })
    })
  }
})
